package com.party.web.web.controller.wechatPlatform;

import com.party.api.dto.wechatPlatform.response.WechatAuthorizerInfoResponse;
import com.party.api.dto.wechatPlatform.response.WechatAuthorizerUserInfoResponse;
import com.party.api.service.wechatPlatform.IWechatPlatformService;
import com.party.core.model.member.DeployType;
import com.party.core.model.member.MemberExternalApp;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.model.wechatPlatform.WechatOpenPlatform;
import com.party.core.service.member.IMemberExternalAppService;
import com.party.core.service.wechat.IWechatDefaultTemplateService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenPlatformService;
import com.party.web.biz.openPlatform.AuthorizationBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;


/**
 * 授权
 */
@Controller
@RequestMapping("/openPlatform/authorization")
public class AuthorizationController {

    @Value("#{wechat_platform['wechat.platform.appId']}")
    private String componentAppid;

    @Value("#{wechat_platform['wechat.platform.appSecret']}")
    private String componentAppsecret;

    @Value("#{wechat_platform['wechat.platform.redirectUrl']}")
    private String redirectUrl; // 授权回调地址

    @Autowired
    private IWechatOpenPlatformService wechatOpenPlatformService;

    @Autowired
    private IWechatPlatformService wechatPlatformService;

    @Autowired
    private AuthorizationBizService authorizationBizService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private IMemberExternalAppService memberExternalAppService;

    @Autowired
    private IWechatDefaultTemplateService wechatDefaultTemplateService;

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 获取授权链接
     *
     * @return
     */
    @RequestMapping("getAuthorizeUrl")
    public ModelAndView getAuthorizeUrl() {
        ModelAndView mv = new ModelAndView("openPlatform/authorForward");
        String memberId = RealmUtils.getCurrentUser().getId();
        try {
            // 获取preAuthCode
            WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.get();
            String authCode
                    = wechatPlatformService.getPreAuthCode(componentAppid, wechatOpenPlatform.getComponentAccessToken());

            StringBuilder stringBuilder = new StringBuilder(redirectUrl);
            stringBuilder.append("?memberId=").append(memberId);
            String authorizeUrl = wechatPlatformService.getAuthorizeUrl(stringBuilder.toString(), componentAppid, authCode);
            mv.addObject("authorizeUrl", authorizeUrl);
        } catch (Exception e) {
            logger.error("获取授权连接异常：memberId：{}", memberId, e);
        }
        return mv;
    }

    /**
     * 授权回调
     *
     * @param auth_code  授权码
     * @param expires_in 过期时间
     * @return
     */
    @RequestMapping("callBack")
    public ModelAndView callBack(String auth_code, String expires_in, String memberId) {
        ModelAndView mv = new ModelAndView("wechat/boundSetting");
        logger.info("授权扫码完成后进入回调...auth_code：{}；expires_in：{}; memberId: {}", auth_code, expires_in, memberId);
        try {
            String accessToken = wechatOpenPlatformService.get().getComponentAccessToken();

            // 获取授权信息
            WechatAuthorizerInfoResponse authorizationInfo
                    = wechatPlatformService.getAuthorizationInfo(componentAppid, accessToken, auth_code);
            if (null == authorizationInfo){
                logger.error("获取授权者信息异常");
                return mv;
            }

            WechatOpenMember openMember = authorizationBizService.saveAuthorizerInfo(authorizationInfo, memberId);

            if (authorizationInfo.getAuthorization_info() != null) {
                String authorizerAppid = authorizationInfo.getAuthorization_info().getAuthorizer_appid();

                // 获取授权者信息
                WechatAuthorizerUserInfoResponse authorizerInfo
                        = wechatPlatformService.getAuthorizerInfo(componentAppid, authorizerAppid, accessToken);
                WechatOpenMember wechatOpenMember
                        = authorizationBizService.saveAuthorizerBaseInfo(authorizerInfo, openMember);
                mv.addObject("grantor",wechatOpenMember);

                // 授权后, 设置默认的模板信息
                List<String> eventNames = Arrays.asList("众筹成功推送", "众筹支持消息推送", "收到众筹回复推送");
                String r = wechatDefaultTemplateService.defaultTemplateMessage(eventNames, memberId, true);
                logger.info("绑定商户默认模板的信息: {}", r);
            }
        } catch (Exception e) {
            logger.error("授权回调异", e);
        }
        return mv;
    }


    /**
     * 获取授权者信息
     * @return 交互数据
     */
    @RequestMapping(value = "getAuthorizer")
    public ModelAndView getAuthorizer(){
        ModelAndView modelAndView = new ModelAndView();
        MemberGroup member = RealmUtils.getCurrentUser();
        // 修改
        MemberExternalApp memberExternalApp
                = memberExternalAppService.findByMemberIdAndDeployType(member.getId(),
                DeployType.AUTHORIZATION.getCode());

        if (null != memberExternalApp){
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.get(memberExternalApp.getExternalAccountId());
            modelAndView.addObject("authorizer", wechatOpenMember);
        }
        return modelAndView;
    }

    /**
     * 用户是否授权
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "isAuthorize")
    public AjaxResult isAuthorize(){
        AjaxResult ajaxResult = new AjaxResult();
        MemberGroup member = RealmUtils.getCurrentUser();

        // 修改
        boolean isAuthorize = wechatOpenMemberService.isAuthorize(member.getId());
        if (isAuthorize){
            ajaxResult.setData(true);
        }
        else {
            ajaxResult.setData(false);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }
}
